const { LoginSql } = require('../model/user')
const { useSetToken } = require('../utils/use')


/**
 * 登录
 */
exports.Login = async (req, res) => {
  try {
    const { user_name, user_pwd } = req.body

    if (!user_name || !user_pwd) {
      res.jsonFail(400, '缺少参数')
    }

    const result = await LoginSql(user_name, user_pwd)

    if (result.length === 0) {
      return res.jsonFail(10001)
    }

    const data = {
      id: result[0]?.user_id,
      user_name: result[0]?.user_name
    }

    res.jsonSuccess({
      ...data,
      token: useSetToken(data)
    })
  } catch (error) {
    res.jsonFail(400, error.message || '登录失败')
  }
}
